import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/AppConfig/LocalStorage.dart';
import 'package:sph_driver/http/NoLoadingPostApi.dart';
import 'package:sph_driver/http/api.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/RouteAct.dart';
import '../../AppConfig/ShowDialog.dart';
import '../../http/NoLoadingGetApi.dart';
import '../../l10n/messages.dart';
import 'dart:io';
import 'package:image/image.dart' as img;
import 'FeedbackProgress.dart';
class FeedbackDetails extends StatefulWidget {
  const FeedbackDetails({super.key, required this.parentId});
  final String parentId;
  @override
  State<FeedbackDetails> createState() => _FeedbackDetailsState();
}

class _FeedbackDetailsState extends State<FeedbackDetails> {
  List chooseTitle =["举报问题：货源广告、诈骗订金、信息泄漏等","账号无法使用：登录异常、账号无法认证、资料修改等","货源异常：运价低、常跑线路货少、虚假货源等",
    "找货不方便：信息推送不准、页面信息杂乱、抢不到货等","客服体验：联系不上、无法解决问题、处理速度慢等","平台规则/保障：规则不合理、规则变更频繁等","其他反馈"];
  String writeText="";
  int checkNo =-1;
  List imageList=[];
  List dataList=[];
  List base64List=[];
  List getImage=[];
  final ImagePicker picker = new ImagePicker();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getPageAction();
  }
  void getPageAction(){
    NoLoadinggetApiManager.getData(
      context,
      "api/system/dev/dict/list",
      {'category':'BIZ','parentId':widget.parentId},
          (responseData)  {
        setState(() {
          dataList=responseData['data'];
        });

      },
    );
  }

  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));

    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();

  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);


    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    base64List.add(base64String);
  }
  Future<void> uploadSingleFile(String fileData) async {
    var random = Random();
    NoLoadingApiManager.postData(
      context, // 上下文对象，用于显示提示信息等
      'api/system/dev/file/uploadSingleFile',
      {
        "type":"FeedbackDocument",
        "fileName":(random.nextInt(90) + 10).toString(),
         "fileFormat":"jpg",
        "fileData":fileData,

      }, // 查询参数，如果没有可以传递null
          (responseData)  {
        setState(() {
          getImage.add(responseData['data']);
          if(getImage.length==base64List.length){
            upLoadAct();
          }
        });
      },
    );
  }
void upLoadAct()async{

    String? driverId = await UserIdManager.getUserID();
    ApiManager.postData(
      context,
      'api/system/system/feedback/add',
      {
        "userType": "DRIVER",
        "userId": driverId,
        "secondStageId": dataList[checkNo]['id'],
        "feedContent": writeText,
        "imagePath":getImage,
        "firstStageDesc": dataList[checkNo]['dictLabel'],
      },
          (responseData) {
        setState(() {
          Navigator.pop(context);
          BrnToast.show(
            "提交成功",
            context,
            duration: BrnDuration.short,
          );
        });
      },
    );

}
  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
      backgroundColor: MyColors.backgreyColor,
      appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
        leading: IconButton(icon: Icon(Icons.arrow_back_ios,color: Colors.black,),onPressed: (){Navigator.pop(context);},),
        title: Text(messages['意见反馈'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        actions: [
          TextButton(onPressed: (){
            Navigator.push( context, FadeRoute(page:FeedbackProgress()));
          },
              child: Text("意见反馈记录",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 14.sp),))
        ],
      ),
      body: Column(
        children: [
          Expanded(child:
          ListView(
            children: [
              Container(
                color: Colors.white,
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                // height:chooseTitle.length *60,
                child:Column(
                  children: [
                    SizedBox(height: 10.h,),
                    Row(
                      children: [
                        SizedBox(width: 20.w,),
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("请选择反馈问题的类型",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Container(
                      height:dataList.length *40.h,
                      child: ListView.builder(
                        physics: NeverScrollableScrollPhysics(),
                        itemCount: dataList.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Row(
                            children: [
                              SizedBox(width: 10.w,),
                              IconButton(onPressed: (){
                                setState(() {

                                    checkNo=index;

                                });
                              }, icon:checkNo!=index?
                              Icon(Icons.panorama_fish_eye,color: Colors.black26,): Icon(Icons.check_circle_outline,color: MyColors.themeColor,)
                              ),
                              Container(
                                width: 260.w,
                                child:    Text(dataList[index]['dictLabel'],
                                  softWrap: true,
                                  overflow: TextOverflow.visible,
                                  style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                              ),

                            ],
                          );
                        },
                      ),
                    ),

                  ],
                ),

              ),
              SizedBox(height: 8.h,),
              Container(
                height: 160.h,
                color: Colors.white,
                margin: EdgeInsets.only(left: 10.w,right: 10.w,),
                child:Column(
                  children: [
                    SizedBox(height: 10.h,),
                    Row(
                      children: [
                        SizedBox(width: 20.w,),
                        Text("*",style: TextStyle(color: MyColors.themeColor,fontSize: 16.sp),),
                        Text("建议内容",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Container(
                      margin: EdgeInsets.only(left: 10.w,right: 10.w),
                      child: BrnInputText(
                        maxHeight: 140,
                        minHeight: 140,
                        minLines: 1,
                        maxLength: 200,
                        autoFocus: false,
                        bgColor: MyColors.backgreyColor!,
                        textString: writeText ?? '',
                        textInputAction: TextInputAction.newline,
                        maxHintLines: 20,
                        hint: '请输入您的宝贵建议',
                        padding: EdgeInsets.fromLTRB(20, 10, 20, 14),
                        onTextChange: (text) {
                          print(text);
                          writeText = text;
                          setState(() {});
                        },
                        onSubmit: (text) {
                          print(text);
                        },
                      ),
                    ),

                  ],
                ),
              ),
              Container(
                color: Colors.white,
                margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
                height: 162.h,
                child: Column(
                  children: [
                    SizedBox(
                      height: 18.h,
                    ),
                    Row(
                      children: [
                        SizedBox(width: 10.h,),
                        Text("上传图片",style: TextStyle(color: Colors.black,fontSize: 16.sp),),
                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 10.w,),
                        GestureDetector(
                          child: Container(
                            height: 60.h,
                            width:60.w,
                            child: imageList.length>0?Stack(
                              children: [
                                Image.file(imageList[0]!,fit: BoxFit.cover, ),
                                Positioned(
                                  top: -10,
                                  right:-10,
                                  child: IconButton(
                                    icon: Icon(Icons.highlight_off,color: MyColors.textColor,size: 30,),
                                    onPressed: () {
                                      setState(() {
                                        imageList.remove(imageList[0]);
                                        base64List.remove(base64List[0]);
                                      });
                                    },
                                  ),
                                ),
                              ],
                            )
                                :Image.asset("lib/Images/PersonCenter/意见反馈上传照片.png",),
                          ),
                          onTap: (){
                            showModalBottomSheet(
                                context: context, builder: (BuildContext context) {
                              return Container(
                                height: 140.h,
                                color: Colors.white,
                                child: Column(
                                  children: [
                                    SizedBox(height: 8.h,),
                                    Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                    SizedBox(height: 18.h,),
                                    Row(
                                      children: [
                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child:   Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                        var status = await Permission.photos.request();
                                        if(status==PermissionStatus.denied){
                                        showPhotosFirstDialog(context);
                                        }else if(status==PermissionStatus.permanentlyDenied){
                                        showPhotosDialog(context);
                                        }else{
                                            Navigator.of(context).pop();
                                            final pickerImages = await picker.pickImage(source: ImageSource.gallery);
                                            if(mounted) {
                                              setState(() {
                                                if (pickerImages != null) {
                                                  setState(() {
                                                    imageList.length > 1 ?
                                                    imageList[0] =
                                                        File(pickerImages.path)
                                                        : imageList.add(File(
                                                        pickerImages.path));
                                                    printImageMemorySize(
                                                        imageList[0]!);
                                                    compressImage(
                                                        imageList[0]!);
                                                  });
                                                } else {
                                                  print('没有照片可以选择');
                                                }
                                              });
                                            }
                                            };
                                          },
                                        ),

                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child: Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                            var status = await Permission.camera.request();
                                            if(status==PermissionStatus.denied){
                                              showCameraFirstDialog(context);
                                            }else if(status==PermissionStatus.permanentlyDenied){
                                              showCameraDialog(context);
                                            }else {
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.camera);
                                              if (mounted) {
                                                setState(() {
                                                  if (pickerImages != null) {
                                                    setState(() {
                                                      imageList.length > 1 ? imageList[0] = File(pickerImages.path)
                                                          : imageList.add(File(pickerImages.path));
                                                      printImageMemorySize(
                                                          imageList[0]!);
                                                      compressImage(
                                                          imageList[0]!);
                                                    });
                                                  } else {
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            }
                                          },
                                        ),

                                      ],
                                    ),
                                  ],
                                ),
                              );
                            });
                          },
                        ),
                        SizedBox(width: 10.w,),
                        GestureDetector(
                          child:
                          Container(
                            height: 60.h,
                            width:imageList.length>0?60.w:0,
                            child: imageList.length>1?Stack(
                              children: [
                                Image.file(imageList[1]!,fit: BoxFit.cover, ),
                                Positioned(
                                  top: -10,
                                  right:-10,
                                  child: IconButton(
                                    icon: Icon(Icons.highlight_off,color: MyColors.textColor,size: 30,),
                                    onPressed: () {
                                    setState(() {
                                      imageList.remove(imageList[1]);
                                      base64List.remove(base64List[1]);
                                    });
                                    },
                                  ),
                                ),
                              ],
                            )
                                :Image.asset("lib/Images/PersonCenter/意见反馈上传照片.png",),
                          ),

                          onTap: (){
                            showModalBottomSheet(
                                context: context, builder: (BuildContext context) {
                              return Container(
                                height: 140.h,
                                color: Colors.white,
                                child: Column(
                                  children: [
                                    SizedBox(height: 8.h,),
                                    Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                    SizedBox(height: 18.h,),
                                    Row(
                                      children: [
                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child:   Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                            var status = await Permission.photos.request();
                                            if(status==PermissionStatus.denied){
                                              showPhotosFirstDialog(context);
                                            }else if(status==PermissionStatus.permanentlyDenied){
                                              showPhotosDialog(context);
                                            }else {
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.gallery);
                                              if (mounted) {
                                                setState(() {
                                                  if (pickerImages != null) {
                                                    setState(() {
                                                      imageList.length > 1 ? imageList[1] = File(pickerImages.path)
                                                          : imageList.add(File(pickerImages.path));
                                                      printImageMemorySize(
                                                          imageList[1]!);
                                                      compressImage(
                                                          imageList[1]!);
                                                    });
                                                  } else {
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            }
                                          },
                                        ),
                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child: Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["拍照"],style: TextStyle(color: Colors.black),),
                                            ],
                                          ),
                                          onTap: ()async{
                                            var status = await Permission.camera.request();
                                            if(status==PermissionStatus.denied){
                                              showCameraFirstDialog(context);
                                            }else if(status==PermissionStatus.permanentlyDenied){
                                              showCameraDialog(context);
                                            }else{
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.camera);
                                              if(mounted){
                                                setState(() {

                                                  if(pickerImages != null){
                                                    setState(() {
                                                      imageList.length>1?imageList[1] = File(pickerImages.path)
                                                          :imageList.add(File(pickerImages.path));
                                                      printImageMemorySize(
                                                          imageList[1]!);
                                                      compressImage(
                                                          imageList[1]!);
                                                    });
                                                  }else{
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            }
                                          },


                                        ),

                                      ],
                                    ),
                                  ],
                                ),
                              );
                            });
                          },
                        ),
                        SizedBox(width: 10.w,),
                        GestureDetector(
                          child: Container(
                            height: 60.h,
                            width:imageList.length>1?60.w:0,
                            child: imageList.length>2?Stack(
                              children: [
                                Image.file(imageList[2]!,fit: BoxFit.cover, ),
                                Positioned(
                                  top: -10,
                                  right:-10,
                                  child: IconButton(
                                    icon: Icon(Icons.highlight_off,color: MyColors.textColor,size: 30,),
                                    onPressed: () {
                                      setState(() {
                                        base64List.remove(base64List[2]);
                                        imageList.remove(imageList[2]);
                                      });
                                    },
                                  ),
                                ),
                              ],
                            )
                                :Image.asset("lib/Images/PersonCenter/意见反馈上传照片.png",),
                          ),

                          onTap: (){
                            showModalBottomSheet(
                                context: context, builder: (BuildContext context) {
                              return Container(
                                height: 140.h,
                                color: Colors.white,
                                child: Column(
                                  children: [
                                    SizedBox(height: 8.h,),
                                    Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                    SizedBox(height: 18.h,),
                                    Row(
                                      children: [
                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child:   Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                            var status = await Permission.photos.request();
                                            if(status==PermissionStatus.denied){
                                              showPhotosFirstDialog(context);
                                            }else if(status==PermissionStatus.permanentlyDenied){
                                              showPhotosDialog(context);
                                            }else {
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.gallery);
                                              if (mounted) {
                                                setState(() {
                                                  if (pickerImages != null) {
                                                    setState(() {
                                                      imageList.length > 1 ? imageList[2] = File(pickerImages.path)
                                                          : imageList.add(File(pickerImages.path));
                                                      printImageMemorySize(
                                                          imageList[2]!);
                                                      compressImage(
                                                          imageList[2]!);
                                                    });
                                                  } else {
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            }
                                          },
                                        ),

                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child: Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                            var status = await Permission.camera.request();
                                            if(status==PermissionStatus.denied){
                                              showCameraFirstDialog(context);
                                            }else if(status==PermissionStatus.permanentlyDenied){
                                              showCameraDialog(context);
                                            }else {
                                              Navigator.of(context).pop();
                                              final pickerImages = await picker.pickImage(source: ImageSource.camera);
                                              if (mounted) {
                                                setState(() {
                                                  if (pickerImages != null) {
                                                    setState(() {
                                                      imageList.length > 1 ? imageList[2] = File(pickerImages.path)
                                                          : imageList.add(File(pickerImages.path));
                                                      printImageMemorySize(
                                                          imageList[2]!);
                                                      compressImage(
                                                          imageList[2]!);
                                                    });
                                                  } else {
                                                    print('没有照片可以选择');
                                                  }
                                                });
                                              };
                                            }
                                          },
                                        ),

                                      ],
                                    ),
                                  ],
                                ),
                              );
                            });
                          },
                        ),
                      ],

                    ),
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 10.h,),
                        Text("最多可上传3个凭证",style: TextStyle(color: Colors.black26,fontSize: 12.sp),),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                        color:MyColors.themeColor,
                        borderRadius: BorderRadius.all(Radius.circular(30))),
                    width: double.infinity,
                    child: TextButton(
                      child: Text("提交",style: TextStyle(color: Colors.white,fontSize: 14.sp),),

                      onPressed: ()async{
                        if(checkNo==-1){
                          BrnToast.show("请选择问题类型", context);
                        }else if(writeText==""){
                          BrnToast.show("请填写建议内容", context);
                        }else{
                          if(base64List.length>0) {
                            for (int i = 0; i < base64List.length; i++) {
                              String index = base64List[i];
                              uploadSingleFile(index);
                            }
                          }else{
                            upLoadAct();
                          }
                        }
                      },
                    )
                ),
              ],
            ),
          ),

        ],
      ),
    );
  }
}
